<template>
  <div v-loading="upLoading" class="box-layout" element-loading-text="数据加载中">
    <div class="box-title pointer" @click="goDetail">

      <p class="title">
        <span v-if="detail.name.length<8" class="webfont-Medium ">{{ detail.name }}</span>
        <el-tooltip v-else class="item" effect="dark" :content="detail.name" placement="top">
          <span class="webfont-Medium  overflow-ellipsis">{{ showName }}</span>
        </el-tooltip>
        <!-- <i class="iconfont icon-edit" @click="handleEditShow"></i> -->
      </p>
      <!-- <div v-else style="width: 80%;padding: 14px 12px;">
        <el-input ref="input" v-model.trim="inputStr" :placeholder="detail.name" size="medium" @blur="handleEnterOrBlur"
          @keyup.enter.native="handleEnterOrBlur"></el-input>
      </div> -->

    </div>

    <div class="box-bottom">
      <div class="box-info flex">
        <p>
          <span class="title">关键词数</span>
          <span>{{ detail.zong }}</span>
        </p>
        <p v-if="type==='commonality'">
          <span class="title">所有者</span>
          <span class="title_text">{{ detail.nick_name?detail.nick_name:'-' }}</span>
        </p>
        <p>
          <span class="title">修改时间</span>
          <span>{{ updateTime }}</span>
        </p>
      </div>

      <div class="flex box-footer">
        <div>
          <el-tooltip class="item" effect="dark" content="下载词库" placement="top">
            <p class="pointer" @click="handleDown"><i class="iconfont icon-down"></i></p>
          </el-tooltip>
        </div>
        <div>
          <el-tooltip class="item" effect="dark" content="添加至" placement="top">
            <p class="pointer" @click="handleAddTo"><i class="iconfont icon-a-Vector2"></i></p>

          </el-tooltip>
        </div>
        <div>
          <el-tooltip class="item" effect="dark" content="创建副本" placement="top">
            <p class="pointer" @click="handleCopy"><i class="iconfont icon-copy"></i></p>
          </el-tooltip>
        </div>
        <div v-if="roleName==='admin'||roleName==='visitor'||userId===detail.uid">
          <el-tooltip class="item" effect="dark" content="删除词库" placement="top">
            <p class="pointer" @click="handleDel"><i class="iconfont icon-del"></i></p>
          </el-tooltip>
        </div>

      </div>

      <el-dialog title="创建副本" :visible.sync="copyVisible" width="548px">
        <el-form ref="copyForm" :model="copyForm" size="small" label-position="top" :rules="copyRules">
          <el-form-item label="词库名称" prop="name">
            <el-input
              v-model.trim="copyForm.name"
              autocomplete="off"
              style="width: 380px;"
              :placeholder="copyForm.placeholder"
              @focus="handleInputFocus"
            ></el-input>
          </el-form-item>
          <el-form-item label="创建至">
            <el-select v-model="copyForm.teamId" placeholder="请选择词库类型">
              <el-option label="个人词库" :value="''"></el-option>
              <el-option v-if="teamId" label="公共词库" :value="teamId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancel-btn defult" @click="handleCloseCopy">取 消</el-button>
          <el-button type="success" class="defult" :disabled="copyDis" @click="handleSubCopy">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog title="添加至广告组" :visible.sync="addToVisible" width="600px" @close="handleCloseAddForm">
        <el-form ref="addToForm" :model="addToForm" size="small" label-position="top">
          <el-form-item label="词库">
            <div>{{ detail.name }}</div>
          </el-form-item>
          <el-form-item
            label="添加至"
            :rules="[
              { required: true, message: '请选择广告组', trigger: 'blur' }]"
            prop="adList"
          >
            <choose-adgroup v-model="addToForm.adList" @change="adlistChange"></choose-adgroup>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button class="cancel-btn defult" @click="handleCloseAddForm">取 消</el-button>
          <el-button v-loading="addLoading" class="defult" type="success" :disabled="addLoading" @click="handleSubAddForm">确 定</el-button>
        </div>
      </el-dialog>

    </div>
  </div>
</template>
<script>
import chooseAdgroup from '../../components/chooseAdgroup.vue'
import {
  copyWordsList, // 复制词库接口
  downloadWords, // 下载词库接口
  UpWordsUser, // 修改词库
  deleWordsList, // 删除词库
  shiftAdvGroup, // 移至广告组
  reallocate // 词库重名验证
} from '@/api/tool.js'

import {
  getTime
} from '@/utils/moment.js'
export default {
  name: '', // ·������
  components: {
    chooseAdgroup
  },
  props: {
    type: {
      default: 'commonality',
      type: String
    },
    storeInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    var validateSerialName = (rule, value, callback) => {
      if (!value) {
        return callback()
      }

      if (value.length < 3 || value.length > 20) {
        callback(new Error('长度在3到20个字符'))
      }

      var regTextChar = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/
      if (value === '') {
        callback(new Error('请输入词库名称'))
      } else {
        const flag = regTextChar.test(value)
        const reg = new RegExp(/\s/g) // 清空字符自中所有空格
        if (!flag || reg.test(value)) return callback(new Error('只能由汉字,字母,数字,下划线,横杠组成'))
        const obj = {
          name: value,
          teamId: this.copyForm.teamId
        }
        reallocate(obj).then(res => {
          // console.log(res, '重名验证')
          if (res.data.code * 1 === 20000) {
            return callback()
          } else {
            return callback(new Error('词库名称不得重复'))
          }
        })
      }
    }
    return {
      detail: {},
      upLoading: false,
      inputShow: false,
      inputStr: '',
      copyVisible: false, // 创建副本弹窗的显示
      copyDis: false,
      copyForm: { // 创建副本的表单
        name: '',
        placeholder: '',
        teamId: ''
      },
      copyRules: {
        name: [{
          validator: validateSerialName,
          trigger: 'blur'
        }]
      },
      addToVisible: false, // 添加至广告组的弹窗显示
      addLoading: false,
      addToForm: { // 添加至广告组的表单
        adList: []
      }

    }
  },
  computed: {
    teamId() {
      return this.$store.state.team.teamId
    },

    showName() {
      if (this.detail.name && this.detail.name.length > 8) {
        return this.detail.name.substring(0, 8) + '...'
      } else {
        return this.detail.name || ''
      }
    },
    roleName() {
      return this.$store.state.user.userInfo.roleName
    },
    userId() {
      return this.$store.state.user.userInfo.userId
    },

    updateTime() {
      if (this.detail.updateAt) {
        return getTime({
          time: this.detail.updateAt
        })
      } else {
        return ''
      }
    }

  },
  watch: {
    storeInfo: {
      deep: true,
      immediate: true,
      handler: function(newV, oldV) {
        this.detail = JSON.parse(JSON.stringify(newV))
      }
    }
  },
  // ������
  created() {},
  // ���غ�
  mounted() {

  },
  // ���ٺ�
  destroyed() {

  },

  // ����
  methods: {
    handleInputFocus() {
      const {
        name,
        placeholder
      } = this.copyForm
      if (!name) {
        this.copyForm.name = placeholder
      }
    },

    // 去详情页面
    goDetail() {
      this.$router.push({
        name: 'wordDetail',
        query: {
          uid: this.detail.uid,
          id: this.detail.wordUserId,
          name: this.detail.name,
          team: this.detail.teamId

        }
      })
    },
    // 显示输入框
    handleEditShow() {
      this.inputShow = true
      this.inputStr = this.detail.name
      this.$nextTick(() => {
        this.$refs.input.focus()
      })
    },

    // handleEnterOrBlur() {
    //   if (this.inputStr && this.inputStr !== this.detail.name && this.inputStr !== this.detail.name) {
    //     if (this.inputStr.length < 3 || this.inputStr.length > 20) {
    //       this.$message.closeAll()
    //       this.$message({
    //         duration: 1500,
    //         message: '词库名称长度为3到20位',
    //         type: 'error'
    //       })
    //       return false
    //     }
    //     var regTextChar = /^[\u4e00-\u9fa5A-Za-z0-9\-\_]*$/
    //     const reg = new RegExp(/\s/g) // 清空字符自中所有空格
    //     if (!regTextChar.test(this.inputStr) || reg.test(this.inputStr)) {
    //       this.$message.closeAll()
    //       this.$message({
    //         duration: 1500,
    //         message: '词库名称只能由汉字,字母,数字,下划线,横杠组成',
    //         type: 'error'
    //       })
    //       return false
    //     }

    //     reallocate({
    //       name: this.inputStr,
    //       teamId: this.detail.teamId
    //     }).then(res => {
    //       if (res.data.code * 1 === 20000) {
    //         this.modifyWordStore()
    //       } else {
    //         this.$message.closeAll()
    //         this.$message({
    //           duration: 1500,
    //           message: '词库名称不可重复',
    //           type: 'error'
    //         })
    //       }
    //     })
    //   }
    //   this.$refs.input.blur()
    //   return this.inputShow = false
    // },

    // 编辑词库
    async modifyWordStore(data) {
      this.upLoding = true
      const {
        wordUserId
      } = this.detail
      const obj = {
        wordUserId,
        name: this.inputStr
      }
      try {
        const res = await UpWordsUser(obj)
        this.upLoding = false
        if (res.data.code * 1 === 20000) {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: res.data.message || '更改词库名称成功',
            type: 'success'
          })
          this.detail.name = this.inputStr
        } else {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: res.data.message || '更改词库名称失败',
            type: 'error'
          })
        }
      } catch (err) {}
    },

    // 下载词库
    async handleDown() {
      if (this.detail.zong * 1 < 1) {
        this.$message.closeAll()
        this.$message({
          duration: 1500,
          message: '该词库暂无关键词,请先添加关键词',
          type: 'error'
        })
        return false
      }

      this.$message({
        duration: 3500,
        message: '正在为您生成文件',
        type: 'info'
      })
      try {
        const res = await downloadWords({
          wordUserId: this.detail.wordUserId
        })
        if (!res.data.code) {
          const blob = new Blob(['\ufeff' + res.data], {
            type: 'text/csv,charset=UTF-8'
          })
          const that = this
          const objectUrl = URL.createObjectURL(blob)
          const a = document.createElement('a')
          a.setAttribute('href', objectUrl)
          a.setAttribute('download', 'YYY_DATA__' + this.detail.name + '词库' +
              '.csv')
          this.$message.closeAll()
          a.click()
        } else {
          this.$message.closeAll()
          this.$message({
            duration: 1500,
            message: '生成文件失败',
            type: 'error'
          })
        }
      } catch (err) {
        this.$message.closeAll()
        this.$message({
          duration: 1500,
          message: '生成文件失败',
          type: 'error'
        })
      }
    },
    // 添加至
    handleAddTo() {
      if (this.detail.zong * 1 < 1) {
        this.$message.closeAll()
        this.$message({
          duration: 1500,
          message: '该词库暂无关键词,请先添加关键词',
          type: 'error'
        })
        return false
      }

      this.addToVisible = true
    },
    // 取消添加至广告组
    handleCloseAddForm() {
      this.addToForm.adList = []
      this.$refs['addToForm'].resetFields()

      this.$nextTick(() => {
        this.addToVisible = false
      })
    },

    // 提交添加至广告组
    async handleSubAddForm() {
      console.log(this.addToForm.adList)
      this.$refs.addToForm.validate(async(valid) => {
        if (valid) {
          this.addLoading = true
          const list = this.addToForm.adList.map(item => {
            const data = {
              currencyType: this.$store.state.user.unit,
              teamId: this.$store.state.team.teamId,
              keywords: [] // 写死
            }
            // if (item[0] === 'default') {
            //   data.orgId = '' // 写死
            //   data.uuid = '', // 写死
            //   data.campaignGroupId = item[1]
            //   data.campaignId = item[2]
            //   data.adgroupId = item[3]
            // } else {
              data.uuid = item[0] // 写死
              data.orgId = item[1] // 写死
              data.campaignId = item[2]
              data.adgroupId = item[3]
            // }

            return data
          })
          const obj = {
            wordUserId: this.detail.wordUserId,
            teamId: this.$store.state.team.teamId,
            list
          }
          try {
            const res = await shiftAdvGroup(obj)
            this.$message.closeAll()
            this.addLoading = false
            if (res.data.code * 1 === 20000) {
              this.$message({
                duration: 1500,
                message: res.data.message || '添加至广告组成功',
                type: 'success'
              })
              this.handleCloseAddForm()
            } else {
              this.$message({
                duration: 1500,
                message: res.data.message || '添加至广告组失败',
                type: 'error'
              })
            }
          } catch (err) {}
        } else {

        }
      })
    },

    // 点击了创建副本按钮
    handleCopy() {
      this.copyForm.placeholder = this.detail.name + '_副本'
      this.copyForm.teamId = this.detail.teamId
      this.copyVisible = true
    },

    // 取消复制词库
    handleCloseCopy() {
      this.$refs['copyForm'].resetFields()
      this.$nextTick(() => {
        this.copyVisible = false
      })
    },

    // 提交复制创建词库
    handleSubCopy() {
      let {
        name,
        teamId,
        placeholder
      } = this.copyForm
      if (!name) {
        this.copyForm.name = placeholder
        name = placeholder
      }
      this.$refs['copyForm'].validate(async(valid) => {
        if (valid) {
          this.copyDis = true

          const obj = {
            name,
            teamId,
            wordUserId: this.detail.wordUserId
          }

          try {
            const res = await copyWordsList(obj)
            this.copyDis = false
            if (res.data.code * 1 === 20000) {
              this.$emit('copy', obj)
              this.handleCloseCopy()
              this.$message({
                duration: 1500,
                message: res.data.message || '创建词库副本成功',
                type: 'success'
              })
            } else {
              this.$message({
                duration: 1500,
                message: res.data.message || '创建词库副本失败',
                type: 'error'
              })
            }
          } catch (err) {}
        } else {

        }
      })
    },

    // 删除词库
    handleDel() {
      this.$confirm('一旦删除将不可恢复！', '确定要删除该词库吗？', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        confirmButtonClass: 'defult',
        cancelButtonClass: 'defult'
      }).then(async() => {
        try {
          const obj = {
            wordUserId: this.detail.wordUserId,
            teamId: this.$store.state.team.teamId
          }
          const res = await deleWordsList(obj)
          if (res.data.code * 1 === 20000) {
            this.$emit('del', this.detail)
            this.handleCloseCopy()
            this.$message.closeAll()
            this.$message({
              duration: 1500,
              message: res.data.message || '删除词库成功',
              type: 'success'
            })
          } else {
            this.$message({
              duration: 1500,
              message: res.data.message || '删除词库失败',
              type: 'error'
            })
          }
        } catch (err) {}
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }

  }
}
</script>

<style scoped lang="scss">
  .box-layout {
    position: relative;
    width: 100%;
    min-width: 270px;
    height: 185px;
    margin-bottom: 24px;
    overflow: hidden;
    border-radius: 4px;
    background: #FFFFFF;

    .box-title {
      height: 117px;
      display: flex;
      align-items: center;
      justify-content: center;

      p.title {
        max-width: 80%;
        display: flex;

        span {
          display: inline-block;
          margin-right: 12px;
          font-size: 24px;
          line-height: 24px;
          flex: 1;
        }

        i {
          opacity: 0;
          font-size: 16px;
          line-height: 24px;
          color: #ACB6C2;
          transition: opacity .2S;
        }
      }
    }

    .box-bottom {
      position: absolute;
      height: 68px;
      width: 100%;
      bottom: 0;
      overflow: hidden;
    }

    .box-info,
    .box-footer {
      position: absolute;
      bottom: 0;
      width: 100%;
      height: 68px;
      // left: 0;
      // right: 0;
      background: #F1F2F3;
    }

    .box-info {
      cursor: pointer;
      padding: 16px 0;
      p {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        span {
          font-size: 12px;
          line-height: 12px;
          color: #39444E;
        }

        .title {
          padding-bottom: 12px;
          color: rgba(51, 64, 74, 0.8);
        }
        .title_text{
          overflow:hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 1;
          -webkit-box-orient: vertical;
        }
      }
    }

    .box-footer {
      height: 46px;
      bottom: 0px;
      display: flex;
      align-items: center;
      justify-content: center;
      opacity: 0;
      transition: opacity .2S;

      >div {
        height: 46px;
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: center;

        p.pointer {
          height: 36px;
          width: 90%;
          line-height: 36px;
          text-align: center;
        }

        i {
          cursor: pointer;
          font-size: 18px;
          color: #ACB6C2;
        }
      }
    }

  }

  .box-layout:hover {
    .title {
      .icon-edit {
        opacity: 1;
      }
    }
  }

  .box-layout:hover {
    .box-info {
      opacity: 0;
    }

    .box-footer {
      opacity: 1;
    }
  }
</style>
